package mysql

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"time"
)

func ConnectToDatabase(dbName string) (*gorm.DB, error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
		viper.GetString(dbName+".UserName"),
		viper.GetString(dbName+".Password"),
		viper.GetString(dbName+".Host"),
		viper.GetString(dbName+".Port"),
		viper.GetString(dbName+".Database"),
		viper.GetString(dbName+".Charset"))

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})

	sqlDB, err := db.DB()

	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)

	return db, err
}

func CreateDB(db *gorm.DB, model *any) error {
	err := db.AutoMigrate(model)
	return err
}

func main() {
	db, err := ConnectToDatabase("user_db")
	if err != nil {
		fmt.Println("Error connecting to database:", err)
		return
	}

	err = db.AutoMigrate(&DiskList{})
}
